package com.ttech.twitter.stream;

import com.ttech.twitter.socket.TwitterWebSocket;
import com.ttech.twitter.util.DbUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * User: TTACANSEVER
 */
public class TweetSenderThread extends Thread {

    public static final Set<TwitterWebSocket> users = new CopyOnWriteArraySet<TwitterWebSocket>();
    private TwitterStreamer twitterStreamer;

    public TweetSenderThread() throws IOException {
        this.twitterStreamer = new TwitterStreamer();
        twitterStreamer.init();
    }

    public void run(){
        while(true) {
            try {
                String tweet = twitterStreamer.getTweet();
                long currentTime = System.currentTimeMillis();
                if(tweet != null) {
                    for (TwitterWebSocket user : users) {
                        try {
                            user.getConnection().sendMessage(tweet);
                            if(currentTime % 10 == 0) {
                                ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
                                String json = ow.writeValueAsString(DbUtil.getGraphData());
                                user.getConnection().sendMessage("Graph|||" + json);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

